from flask import Blueprint, request, jsonify

from utils.db import db1
from .compan import get_data
import time
from app import create_app
from tasks import make_celery

bp_finan = Blueprint('finan', __name__)

flask_app = create_app()
celery = make_celery(flask_app)


@bp_finan.route('/khjl', methods=['POST', 'GET'])
# @celery.tasks()
def khjl():
    if request.method == 'POST':
        data = get_data()
        c = time.time()
        ctime = c / 360000
        sql1 = """insert into khjltable(company_name,name,tmoney,usermoney) values("%s","%s",%d,%d)""" % (
            data['company_name'], data['name'], int(data['tmoney']), int(data['usermoney']))

        print(sql1)
        db1.update(sql1)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = 'select * from khjltable'
        res = db1.findall(sql)
        return jsonify({"code": 200, "list": res})


@bp_finan.route('/regi', methods=['POST', 'GET'])
def regi():
    if request.method == 'POST':
        data = get_data()

        sql1 = """insert into regilytable(name,tcount) values("%s",0)""" % (data['name'])

        print(sql1)
        db1.update(sql1)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql = 'select * from regilytable'
        res = db1.findall(sql)
        return jsonify({"code": 200, "list": res})


from tasks import celery


@bp_finan.route('/kehu', methods=['POST', 'GET'])
@celery.task()
def kehu():
    if request.method == 'POST':
        data = get_data()
        ctime = int(time.time())
        sql = """insert into usertable(tmoney,name,jigou,khjlid,regiid,status,ctime) values(%d,'%s','%s',%d,%d,1,%d)""" % (
            int(data['tmoney']), data['name'], data['jigou'], int(data['khjlid']), int(data['regiid']), ctime)
        db1.update(sql)
        return jsonify({'code': 200})
